package com.hghivln.shiro;

import com.hghivln.pojo.domain.User;
import com.hghivln.pojo.vo.ActiverUser;
import com.hghivln.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    @Lazy
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 得到用户的登录名
        String phone = token.getPrincipal().toString();
        // 跟据电话号码查询用户是否存在
        User user = userService.queryUserByPhone(phone);
        if (user != null) {
            ActiverUser activerUser = new ActiverUser();
            activerUser.setUser(user);
            return new SimpleAuthenticationInfo(activerUser,user.getPassword(), ByteSource.Util.bytes(user.getSalt()),this.getName());
        } else {
            return null ;
        }

    }

}
